package com.jprocms.module.cms.redis;

import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.stereotype.Repository;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;


/**
 * Redis 锁 DAO
 *
 * @author JPROCMS
 */
@Repository
public class LockRedisDAO {

    @Resource
    private RedissonClient redissonClient;

    public void lock(String lockKey, Long timeoutMillis, Runnable runnable) {
        RLock lock = redissonClient.getLock(lockKey);
        try {
            lock.lock(timeoutMillis, TimeUnit.MILLISECONDS);
            // 执行逻辑
            runnable.run();
        } finally {
            lock.unlock();
        }
    }

}
